package com.h3c.nem.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eos.common.custom.BusinessException;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.h3c.nem.entity.SdUploadFile;
import com.h3c.nem.service.ITbNewerTaskService;
import com.h3c.nem.dto.TbNewerTaskDTO;
import com.h3c.nem.utils.ReturnCodeData;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import org.springframework.web.bind.annotation.RestController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Copyright (C), 2020-2020, h3c
 * FileName: TbNewerTaskController
 *
 * @Author: l22886
 * @Date: 2022-01-24
 * Description: tb_newer_task controller
 * Version: 1.0
 */
@Api(tags = " TbNewerTask 接口")
@Slf4j
@RestController
@CrossOrigin
@RequestMapping(value = "/tbNewerTask",produces = "application/json;charset=utf-8")
public class TbNewerTaskController {

    @Resource
    private ITbNewerTaskService tbNewerTaskService;

    @Autowired
    private CommController commController;

    /**
     * @title: queryFuzzyListForPage
     * @description: 列表分页模糊查询
     * @params: [ paramsDTO, currentPage, pageSize ]
     * @return: org.springframework.http.ResponseEntity
     * @createTime: 2022-01-24
     * @version: 1.0
     * @author: l22886
     */
    @ApiOperation(value = "列表分页查询", notes = "列表分页查询")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "paramsDTO", value = "实体参数信息", required = true, dataType = "TbNewerTaskDTO", paramType = "query"),
        @ApiImplicitParam(name = "currentPage", value = "当前页", required = true, dataType = "Integer", paramType = "query"),
        @ApiImplicitParam(name = "pageSize", value = "一页数据条数", required = true, dataType = "Integer", paramType = "query")
    })
    @RequestMapping(value = "/queryFuzzyListForPage", method = RequestMethod.GET)
    public ResponseEntity<JSONObject> queryFuzzyListForPage(@ModelAttribute TbNewerTaskDTO paramsDTO,
                                                            @RequestParam(name = "currentPage") Integer currentPage,
                                                            @RequestParam(name = "pageSize") Integer pageSize) {
        log.info("准备执行  列表分页模糊查询，传入的参数为：" + JSON.toJSONString(paramsDTO));
        JSONObject data = new JSONObject();
        try {
            //分页
            Page<TbNewerTaskDTO> page = PageHelper.startPage(currentPage, pageSize);
            //执行
            List<TbNewerTaskDTO> resultDTOList = tbNewerTaskService.selectFuzzyByDto(paramsDTO);
            PageInfo<TbNewerTaskDTO> pageInfo = page.toPageInfo();
            pageInfo.setList(resultDTOList);
            data.put("data",pageInfo);
            data.put("msg", "列表分页模糊查询成功");
            data.put("code", ReturnCodeData.SUCCESS);
        } catch (Exception e) {
            log.error("执行列表分页模糊查询异常，异常信息为：", e);
            data.put("msg", e.toString());
            data.put("code", ReturnCodeData.FAIL);
        }
        log.info("执行列表分页模糊查询完成，准备返回的结果为：" + JSON.toJSONString(data));
        return new ResponseEntity<>(data, HttpStatus.ACCEPTED);
    }

    @RequestMapping(value = "/getTaskFileList", method = RequestMethod.GET)
    public ResponseEntity<JSONObject> getTaskFileList(String taskId) {
        JSONObject data = new JSONObject();
        try {
            //执行
            List<SdUploadFile> resultDTOList = tbNewerTaskService.getTaskFileList(taskId);
            data.put("data", resultDTOList);
            data.put("msg", "查询成功");
            data.put("code", ReturnCodeData.SUCCESS);
        } catch (Exception e) {
            log.error("执行查询异常，异常信息为：", e);
            data.put("msg", e.toString());
            data.put("code", ReturnCodeData.FAIL);
        }
        return new ResponseEntity<>(data, HttpStatus.ACCEPTED);
    }

    /**
     * @title: queryListForPage
     * @description: 列表分页精确查询
     * @params: [ paramsDTO, currentPage, pageSize ]
     * @return: org.springframework.http.ResponseEntity
     * @createTime: 2022-01-24
     * @version: 1.0
     * @author: l22886
     */
    @ApiOperation(value = "列表分页查询", notes = "列表分页查询")
    @ApiImplicitParams({
    @ApiImplicitParam(name = "paramsDTO", value = "实体参数信息", required = true, dataType = "TbNewerTaskDTO", paramType = "query"),
    @ApiImplicitParam(name = "currentPage", value = "当前页", required = true, dataType = "Integer", paramType = "query"),
    @ApiImplicitParam(name = "pageSize", value = "一页数据条数", required = true, dataType = "Integer", paramType = "query")
    })
    @RequestMapping(value = "/queryListForPage", method = RequestMethod.GET)
    public ResponseEntity<JSONObject> queryListForPage(@ModelAttribute TbNewerTaskDTO paramsDTO,
                                                       @RequestParam(name = "currentPage", required = true) Integer currentPage,
                                                       @RequestParam(name = "pageSize", required = true) Integer pageSize) {
        log.info("准备执行  列表分页查询，传入的参数为：" + JSON.toJSONString(paramsDTO));
        JSONObject data = new JSONObject();
        try {
            //分页
            Page page = PageHelper.startPage(currentPage, pageSize);
            //执行
            List<TbNewerTaskDTO> resultDTOList = tbNewerTaskService.selectFuzzyByDto(paramsDTO);
            PageInfo<TbNewerTaskDTO> pageInfo = page.toPageInfo();
            pageInfo.setList(resultDTOList);
            data.put("data",pageInfo);
            data.put("msg", "列表分页查询成功");
            data.put("code", ReturnCodeData.SUCCESS);
        } catch (Exception e) {
            log.error("执行列表分页查询异常，异常信息为：" + JSON.toJSONString(e));
            data.put("msg", e.toString());
            data.put("code", ReturnCodeData.FAIL);
        }
        log.info("执行列表分页查询完成，准备返回的结果为：" + JSON.toJSONString(data));
        return new ResponseEntity<>(data, HttpStatus.ACCEPTED);
    }


    /**
     * @title: save
     * @description: 数据插入
     * @params: [ paramsDTO ]
     * @return: org.springframework.http.ResponseEntity
     * @createTime: 2022-01-24
     * @version: 1.0
     * @author: l22886
     */
    @ApiOperation(value = "数据插入", notes = "数据插入")
    @ApiImplicitParams({@ApiImplicitParam(name = "paramsDTO", value = "实体参数信息", required = true, dataType = "TbNewerTask", paramType = "body")})
    @RequestMapping(value = "/saveWithFile", method = RequestMethod.POST)
    public ResponseEntity<JSONObject> save(@RequestParam(value = "taskId", required = false) String taskId,
                                           @RequestParam(value = "taskName", required = false) String taskName,
                                           @RequestParam(value = "taskNote", required = false) String taskNote,
                                           @RequestParam(value = "taskEntry", required = false) String taskEntry,
                                           @RequestParam(value = "targetConfigValue", required = false) String targetConfigValue,
                                           @RequestParam(value = "taskValidDate", required = false) String taskValidDate,
                                           @RequestParam(value = "taskExpireDate", required = false) String taskExpireDate,
                                           @RequestParam(value = "approverType", required = false) Integer approverType,
                                           @RequestParam(value = "approverId", required = false) String approverId,
                                           @RequestParam(value = "enableFlag", required = false) Integer enableFlag,
                                           @RequestParam(value = "file", required = false) MultipartFile file) {
        Date exDate = null;
        Date vaDate = null;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        if (StringUtils.isNotBlank(taskExpireDate) && !"null".equals(taskExpireDate)) {
            try {
                exDate = simpleDateFormat.parse(taskExpireDate);
            } catch (ParseException ignore) {}
        }
        if (StringUtils.isNotBlank(taskValidDate) && !"null".equals(taskValidDate)) {
            try {
                vaDate = simpleDateFormat.parse(taskValidDate);
            } catch (ParseException ignore) {}
        }
        TbNewerTaskDTO paramsDTO = new TbNewerTaskDTO(taskId, taskName, taskNote, targetConfigValue, taskEntry,
                vaDate, exDate, approverType, approverId, enableFlag);
        log.info("准备执行 数据插入，传入的参数为：" + JSON.toJSONString(paramsDTO));
        JSONObject data = new JSONObject();
        try {
            //执行 返回taskId
            String result = tbNewerTaskService.insertDto(paramsDTO);
            if (file != null) {
                commController.uploadFile(file, 1, result);
            }
            data.put("data",result);
            data.put("msg", "数据插入成功");
            data.put("code", ReturnCodeData.SUCCESS);
        } catch (Exception e) {
            log.error("执行 数据插入 异常，异常信息为：", e);
            data.put("msg", e.toString());
            data.put("code", ReturnCodeData.FAIL);
        }
        log.info("执行 数据插入完成，准备返回的结果为：" + JSON.toJSONString(data));
        return new ResponseEntity<>(data, HttpStatus.ACCEPTED);
    }

    /**
     * @title: update
     * @description: 数据修改
     * @params: [ paramsDTO ]
     * @return: org.springframework.http.ResponseEntity
     * @createTime: 2022-01-24
     * @version: 1.0
     * @author: l22886
     */
    @RequestMapping(value = "/updateWithFile", method = RequestMethod.POST)
    @Transactional
    public ResponseEntity<JSONObject> update(@RequestParam(value = "taskId", required = false) String taskId,
                                             @RequestParam(value = "taskName", required = false) String taskName,
                                             @RequestParam(value = "taskNote", required = false) String taskNote,
                                             @RequestParam(value = "taskEntry", required = false) String taskEntry,
                                             @RequestParam(value = "targetConfigValue", required = false) String targetConfigValue,
                                             @RequestParam(value = "taskValidDate", required = false) String taskValidDate,
                                             @RequestParam(value = "taskExpireDate", required = false) String taskExpireDate,
                                             @RequestParam(value = "approverType", required = false) Integer approverType,
                                             @RequestParam(value = "approverId", required = false) String approverId,
                                             @RequestParam(value = "enableFlag", required = false) Integer enableFlag,
                                             @RequestParam(value = "file", required = false) MultipartFile file) {
        Date exDate = null;
        Date vaDate = null;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        if (StringUtils.isNotBlank(taskExpireDate) && !"null".equals(taskExpireDate)) {
            try {
                exDate = simpleDateFormat.parse(taskExpireDate);
            } catch (ParseException ignore) {}
        }
        if (StringUtils.isNotBlank(taskValidDate) && !"null".equals(taskValidDate)) {
            try {
                vaDate = simpleDateFormat.parse(taskValidDate);
            } catch (ParseException ignore) {}
        }

        TbNewerTaskDTO paramsDTO = new TbNewerTaskDTO(taskId, taskName, taskNote, targetConfigValue, taskEntry,
                vaDate, exDate, approverType, approverId, enableFlag);
        log.info("准备执行 数据修改，传入的参数为：" + JSON.toJSONString(paramsDTO));
        JSONObject data = new JSONObject();
        try {
            //执行
            String result = tbNewerTaskService.updateDto(paramsDTO);
            if (file != null) {
                commController.uploadFile(file, 1, result);
            }
            data.put("data",result);
            data.put("msg", "数据修改成功");
            data.put("code", ReturnCodeData.SUCCESS);
        } catch (Exception e) {
            log.error("执行 数据修改 异常，异常信息为：", e);
            data.put("msg", e.toString());
            data.put("code", ReturnCodeData.FAIL);
        }
        log.info("执行 数据修改完成，准备返回的结果为：" + JSON.toJSONString(data));
        return new ResponseEntity<>(data, HttpStatus.ACCEPTED);
    }

    /**
     * @title: delete
     * @description: 数据删除
     * @params: [ id ]
     * @return: org.springframework.http.ResponseEntity
     * @createTime: 2022-01-24
     * @version: 1.0
     * @author: l22886
     */
    @ApiOperation(value = "数据删除", notes = "数据删除")
    @ApiImplicitParams({@ApiImplicitParam(name = "paramsDTO", value = "实体参数信息", required = true, dataType = "TbNewerTask", paramType = "body")})
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public ResponseEntity<JSONObject> delete(@RequestBody TbNewerTaskDTO paramsDTO) {
        log.info("准备执行 数据删除，传入的参数为：" + JSON.toJSONString(paramsDTO));
        JSONObject data = new JSONObject();
        try {
            //执行
            Integer result = tbNewerTaskService.deleteDto(paramsDTO);
            data.put("data",result);
            data.put("msg", "数据删除成功");
            data.put("code", ReturnCodeData.SUCCESS);
        } catch (Exception e) {
            log.error("执行 数据删除 异常，异常信息为：", e);
            data.put("msg", "数据删除失败");
            data.put("code", ReturnCodeData.FAIL);
        }
        log.info("执行 数据删除 完成，准备返回的结果为：" + JSON.toJSONString(data));
        return new ResponseEntity<>(data, HttpStatus.ACCEPTED);
    }


    @ApiOperation(value = "发布任务", notes = "发布任务")
    @ApiImplicitParams({@ApiImplicitParam(name = "paramsDTO", value = "实体参数信息", required = true, dataType = "TbNewerTask", paramType = "body")})
    @RequestMapping(value = "/postTask", method = RequestMethod.POST)
    public ResponseEntity<JSONObject> postTask(@RequestBody List<TbNewerTaskDTO> paramsDTO) {
        log.info("准备执行 发布任务，传入的参数为：" + JSON.toJSONString(paramsDTO));
        JSONObject data = new JSONObject();
        try {
            //执行
            String result = tbNewerTaskService.postTask(paramsDTO);
            data.put("data",result);
            data.put("msg", "发布任务成功");
            data.put("code", ReturnCodeData.SUCCESS);
        } catch (Exception e) {
            log.error("执行 发布任务 异常，异常信息为：", e);
            if (e instanceof BusinessException) {
                data.put("msg", e.getMessage());
            } else {
                data.put("msg", "发布任务失败");
            }
            data.put("code", ReturnCodeData.FAIL);
        }
        log.info("执行 发布任务 完成，准备返回的结果为：" + JSON.toJSONString(data));
        return new ResponseEntity<>(data, HttpStatus.ACCEPTED);
    }

}
